﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI.WebControls;
using Core.Authenticated;
using Core.Library;
using DataObject;
using DataObject.Article;
using DataObject.Category;

namespace CMS.Controls.Article
{
    public partial class ArticleManager : AuthenticatedControl
    {
        protected int WaittingForPublish;
        protected int Publish;
        
        protected int CategoryId;
        protected new int Status;
        protected string Keyword;
        protected string Url;
        
        protected int PageIndex;
        protected int PageSize;

        protected void Page_Load(object sender, EventArgs e)
        {
            CategoryId  = Utils.GetIdFromRequestString(Utils.CategoryId, 0);                       
            Status      = Utils.GetIdFromRequestString(Utils.Status, 0);
            Keyword     = Utils.GetIdFromRequestString(Utils.Keyword, string.Empty);                       
            PageIndex   = Utils.GetIdFromRequestString(Utils.PageIndex, SettingValues.PageIndex);
            PageSize    = Utils.GetIdFromRequestString(Utils.PageSize, ConvertUtility.ToInt32(ddlPageSize.SelectedValue));
            Url         = HttpUtility.UrlEncode(Request.Url.ToString());

            if (!string.IsNullOrEmpty(Keyword))
            {
                Keyword = UnicodeUtility.DecodeFrom64(Keyword);
                txtKeyword.Text = Keyword;
            }
            

            if (!IsPostBack)
            {
                ListTreeCategory();

                GetStatistics();

                ListData();
            }
        }

        #region Statistics

        private void GetStatistics()
        {
            Publish             = ArticleController.Article_GetStatistic(CurrentUser.AdminUserId, StatusHelper.IsPublished);            
            WaittingForPublish  = ArticleController.Article_GetStatistic(CurrentUser.AdminUserId, StatusHelper.IsWaitingForPublish); 
        }

        #endregion

        #region List Tree Category                

        private void ListTreeCategory()
        {
            var categories = new List<CategoryObject>();
            CategoryController.GetListTree(categories, (int)CategoryType.Article, 0, Constants.PARENT_ROOT);

            if (categories.Count > 0)
            {
                ddlCategory.DataSource = categories;
                ddlCategory.DataBind();
                ddlCategory.Items.Insert(0, new ListItem("-- Chuyên mục --", "0"));
            }
        }

        #endregion

        #region List Data

        private void ListData()
        {
            var totalRecords = 0;
            lvList.DataSource = ArticleController.Article_GetListSearch(CategoryId, Keyword, Status, PageIndex, PageSize, ref totalRecords);
            lvList.DataBind();

            ltPager.Text = PagerUtility.PageLinks(PageIndex, PageSize, totalRecords, 5,
                                UrlHelpers.ListSearchArticle(cControl.AdminMenuId, CategoryId, Keyword, Status, "{0}", PageSize));

            ddlPageSize.SelectedValue   = PageSize.ToString();
            ddlStatus.SelectedValue     = Status.ToString();
            ddlCategory.SelectedValue   = CategoryId.ToString();
        }

        #endregion

        protected void BtnCreate(object sender, EventArgs e)
        {
            Response.Redirect(UrlHelpers.CreateArticle(Url));
        }

        protected void BtnPublish(object sender, EventArgs e)
        {
            UpdateStatus(StatusHelper.IsPublished);
        }

        protected void BtnIsWaitingForPublish(object sender, EventArgs e)
        {
            UpdateStatus(StatusHelper.IsWaitingForPublish);
        }

        protected void BtnSearch(object sender, EventArgs e)
        {
            RedirecLink();
        }

        protected void ddlPageSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            RedirecLink();
        }

        protected void ddlStatus_SelectedIndexChanged(object sender, EventArgs e)
        {
            RedirecLink();
        }

        protected void ddlCategory_SelectedIndexChanged(object sender, EventArgs e)
        {
            RedirecLink();
        }

        public void RedirecLink()
        {
            var status      = ConvertUtility.ToInt32(ddlStatus.SelectedValue);
            var categoryId  = ConvertUtility.ToInt32(ddlCategory.SelectedValue);
            var pageSize    = ConvertUtility.ToInt32(ddlPageSize.SelectedValue);
            var keyword     = txtKeyword.Text.IndexOf("Từ khóa") != -1 ? string.Empty : txtKeyword.Text;

            Response.Redirect(UrlHelpers.ListSearchArticle(cControl.AdminMenuId, categoryId, 
                                                            UnicodeUtility.EncodeTo64UTF8(keyword), 
                                                            status, SettingValues.PageIndex.ToString(), pageSize));
        }

        private void UpdateStatus(int targetStatus)
        {
            ltMessage.Text = string.Empty;
            var count = 0;
            foreach (ListViewDataItem lvi in lvList.Items)
            {
                var cbItem = (CheckBox)lvi.FindControl("cbItem");
                if (cbItem == null || !cbItem.Checked) continue;

                count++;
                var id = ConvertUtility.ToInt32(lvList.DataKeys[lvi.DisplayIndex].Value);
                if (id > 0)
                {
                    var o = ArticleController.Article_GetById(id);
                    if (o != null)
                        ArticleController.Article_Update_Status(CurrentUser.AdminUserId, id, targetStatus);
                }
            }

            if (count == 0)
                ltMessage.Text = MessageUtility.ShowMessage(string.Empty, "Bạn chưa chọn bài viết nào.", MessageType.Warning);

            ListData();
            GetStatistics();
        }

        protected string GetStatusName(int status)
        {
            switch (status)
            {
                case StatusHelper.IsWaitingForPublish:
                    return "Chờ xuất bản";
                
                case StatusHelper.IsPublished:
                    return "Xuất bản";
                case StatusHelper.IsDeleted:
                    return "Bài đã xóa";
            }
            return string.Empty;
        }

        protected void lvList_ItemCommand(object sender, ListViewCommandEventArgs e)
        {
            if (string.Equals(e.CommandName, "DeleteArticle"))
            {
                var dataItem = (ListViewDataItem)e.Item;
                var id = ConvertUtility.ToInt32(lvList.DataKeys[dataItem.DisplayIndex].Value);

                if (id > 0)
                {
                    ArticleController.Article_Delete(id);
                    //ArticleController.Article_Update_Status(CurrentUser.AdminUserId, id, StatusHelper.IsDeleted);
                    ltMessage.Text = MessageUtility.ShowMessage(null, "Xóa bài viết thành công.", MessageType.Information);
                }
            }
            ListData();
        }
    }
}